from flask import request, jsonify, make_response,session
from user import user_blue
from database.database import User,db
from datetime import datetime
from math import floor
from utils.jsonutil import AlchemyEncoder
import json


# user模块
# 登录
@user_blue.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    uname = data.get('username')
    upass = data.get('password')

    # 判断用户名、密码是否正确
    tmp = User.query.filter_by(username=uname).first()
    if tmp is None:
        return jsonify({'code':200,'message': '用户名错误，请重试。', 'data': None})
    elif tmp.password != upass:
        return jsonify({'code':200,'message': '密码错误，请重试。', 'data': None})
    else:
        # 设置session
        response = jsonify({'code':200,'message': '登录成功！', 'data': None})
        session['username'] = uname
        session['password'] = upass
        return response
    
# 注册
@user_blue.route('/register', methods=['POST'])
def resgister():
    data = request.get_json()
    uname = data.get('username')
    upass = data.get('password')

    # 创建新用户，判断uname是否重复
    tmp = User.query.filter_by(username=uname).first()
    if tmp is None:
        new_user = User(username=uname,nickname="用户"+str(floor(datetime.now().timestamp())),password=upass,user_type=0,create_time=datetime.now())
        db.session.add(new_user)
        db.session.commit()
        return jsonify({'code':200,'message': '注册成功！', 'data': None})
    else:
        return jsonify({'code':200,'message': '用户名已存在，请重试。', 'data': None})
    
# 登出
@user_blue.route('/logout',methods=['DELETE'])
def logout():
    session.clear()
    return jsonify({'code':200,'message': '注销成功！', 'data': None})

# 获取自己的信息
@user_blue.route('/myinfo',methods=['GET'])
def get_my_info():
    uname = session.get('username')
    upass = session.get('password')
    if uname is None or upass is None:
        return jsonify({'code':200,'message': '未登录！', 'data': None})
    else:
        tmp = User.query.filter_by(username=uname).first()
        user = json.loads(json.dumps({
            'uname': tmp.username,
            'nickname': tmp.nickname,
            'create_time': tmp.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'user_type': tmp.user_type
        }))
        
        if tmp is None:
            return jsonify({'code':200,'message': '未登录！', 'data': None})
        else:
            return jsonify({'code':200,'message': '获取成功！', 'data': user})
        
# 根据id获取用户信息
@user_blue.route('/id/<user_id>',methods=['GET'])
def get_user_info(user_id):
    tmp = User.query.filter_by(id=user_id).first()
    if tmp is None:
        return jsonify({'code':200,'message': '用户不存在！', 'data': None})
    else:
        user = json.loads(json.dumps({
            'uname': tmp.username,
            'nickname': tmp.nickname,
            'create_time': tmp.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'user_type': tmp.user_type
        }))
        return jsonify({'code':200,'message': '获取成功！', 'data': user})